# src/data_analysis/analysis_comment.py

import json
import logging
from datetime import datetime
from sqlalchemy.orm import Session
from models.comment_schema import RawComment, AnalyzedComment, CommentTag
from sqlalchemy import text, or_, and_
from data_analysis.comment_analyzer import CommentAnalyzer
from sqlalchemy.orm import Session


logger = logging.getLogger(__name__)

'''
分析入口
'''
def analyze_unprocessed_comments(db: Session):
    """
    分析所有未标记为 is_analyzed=True 的评论
    :param db: 数据库会话
    """
    analyzer = CommentAnalyzer(api_key=os.getenv("DEEPSEEK_API_KEY"))

    # 查询未分析的评论
    comments = db.query(RawComment).filter_by(is_analyzed=False).all()
    logger.info(f"📊 共找到 {len(comments)} 条未分析评论")

    for idx, comment in enumerate(comments):
        if not comment.comment_text or not isinstance(comment.comment_text, str):
            logger.warning(f"⚠️ 第 {idx + 1} 条评论为空，跳过分析")
            comment.is_analyzed = True
            db.commit()
            continue

        result = analyzer.analyze_single({
            "id": comment.id,
            "video_source_id": comment.video_source_id,
            "comment_text": comment.comment_text,
            "like_count": comment.like_count
        })

        if not result:
            logger.warning(f"⚠️ 第 {idx + 1} 条评论分析失败")
            comment.is_analyzed = True
            db.commit()
            continue

        # 构建分析后对象
        analyzed = AnalyzedComment(
            id=result["id"],
            video_source_id=result["video_source_id"],
            original_text=result["original_text"],
            translated_text=result.get("translated_text"),
            primary_label=result.get("primary_label"),
            secondary_labels=json.dumps(result.get("secondary_labels"), ensure_ascii=False),
            confidence_score=result.get("confidence_score"),
            like_count=result.get("like_count", 0)
        )

        db.add(analyzed)

        # 更新原始评论状态
        comment.is_analyzed = True
        db.commit()

        logger.info(f"✅ 已分析第 {idx + 1} 条评论 (ID: {comment.id})")